﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using DGSFramework;
using System.Xml.Linq;
using ActiveUp.Net.Mail;
using OpenPop.Pop3;
using System.Net;
using System.Net.Mail;

namespace Framework
{
    public partial class Contact : System.Web.UI.Page
    {
        public DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public List<udv_Articles> allArt = new List<udv_Articles>();

        protected void Page_Load(object sender, EventArgs e)
        {
            RequiredFieldValidator1.ErrorMessage = Globals.GetLanguage("Vui lòng nhập họ tên hoặc công ty", "Please enter name or company", true);
            txtName.Attributes["placeholder"] = Globals.GetLanguage("Họ tên/Công ty", "Name/Company", true);
        
            RequiredFieldValidator4.ErrorMessage = Globals.GetLanguage("Vui lòng nhập điện thoại", "Please enter the phone", true);
            txtPhone.Attributes["placeholder"] = Globals.GetLanguage("Điện thoại", "Phone", true);
            RequiredFieldValidator3.ErrorMessage = Globals.GetLanguage("Vui lòng nhập email", "Please enter the e-mail", true);
            RegularExpressionValidator1.ErrorMessage = Globals.GetLanguage("Email không đúng định dạng", "Email is malformed", true);
            txtEmail.Attributes["placeholder"] = "Email";
            RequiredFieldValidator5.ErrorMessage = Globals.GetLanguage("Vui lòng nhập tiêu đề liên hệ", "Please enter a contact title", true);
            txtTitle.Attributes["placeholder"] = Globals.GetLanguage("Chủ đề", "Title", true);
            RequiredFieldValidator6.ErrorMessage = Globals.GetLanguage("Vui lòng nhập nội dung", "Please enter the message", true);
            RegularExpressionValidator2.ErrorMessage = Globals.GetLanguage("Nội dung liên hệ ít nhất phải 20 ký tự", "Contact content must be at least 20 characters", true);
            txtContent.Attributes["placeholder"] = Globals.GetLanguage("Vui lòng nhập tiếng việt", "Please type here", true);
            btnSend.Text = Globals.GetLanguage("Gửi", "Send", true);
            btnReset.Text = Globals.GetLanguage("Làm lại", "Redo", true);
        }
        public void InsertDb()
        {
            udv_Contact obj = new udv_Contact()
            {
                Title = Server.HtmlEncode(txtTitle.Text.Trim()),
                AddedDate = DateTime.Now,
                Content = Server.HtmlEncode(txtContent.Text.Trim()),
                Email = Server.HtmlEncode(txtEmail.Text.Trim()),
                FullName = Server.HtmlEncode(txtName.Text.Trim()),
                Tel = Server.HtmlEncode(txtPhone.Text.Trim()),
                Address = "",
                ViewStatus = false,
                ReplyStatus = false
            };

            entity.AddToudv_Contact(obj);
            entity.SaveChanges();
        }

        private bool SendEmail()
        {
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            string serverMail = emailHostSetting.ServerMailSMTP.Trim();
            string port = emailHostSetting.PortMailSMTP.ToString();
            string yourMailAccount = emailHostSetting.MailAccount.Trim();
            string yourMailPassword = Globals.Base64Decode(emailHostSetting.Password.Trim());

            SendMail sm = new SendMail();
            sm.ServerMail = serverMail;
            sm.ServerPort = port;
            sm.SSL = emailHostSetting.SSL.Value;
            sm.YourMailAccount = yourMailAccount;
            sm.YourMailPassword = yourMailPassword;
            sm.SetUpYourServerMail();

            string receive = yourMailAccount;

            XDocument xDocContact = XDocument.Load(Server.MapPath(ConfigPaths.Path_ContactGroup_Xml));
            var listXEContact = xDocContact.Descendants("contact_group")
                .Select(cg => new
                {
                    ID = cg.Element("id").Value.Trim(),
                    Mail = cg.Element("mail").Value.Trim(),
                    ShowName = cg.Element("showname").Value.Trim(),
                    ShowName_en = cg.Element("showname").Value.Trim(),
                    Index = cg.Element("index").Value.Trim(),
                    Group = cg.Element("group").Value.Trim()
                })
                .ToList();
            foreach (var item in listXEContact)
            {
                receive += item.Mail + ",";
            }
            string title = txtTitle.Text.Trim();
            string uEmail = txtEmail.Text.Trim();
            string body = "<p><img src='images/Signature150903.png' /></p>"; 
                body +="<p><b>Họ tên:</b> " + txtName.Text.Trim() + "</p>";
            body += "<p><b>Điện thoại:</b> " + txtPhone.Text.Trim() + "</p>";
            body += "<p><b>Email:</b> " + txtEmail.Text.Trim() + "</p>";
            body += "<p><b>Nội dung liên hệ:</b></p>";
            body += "<p>" + txtContent.Text + "</p>";

            sm.CreateMailObject(uEmail, body, title, emailHostSetting.MailReceive);
            if (sm.MailSending())
            {
                InsertDb();
                return true;
            }
            else
            {
                InsertDb();
                return false;
            }
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            recaptcha.Validate();
            if (recaptcha.IsValid)
            {
                lblCaptchaMessage.InnerText = "";
                SendEmail();
                //InsertDb();
                ResetAllFields();
                lblAlertContact.Text = "Chân thành cảm ơn quý khách đã liên hệ với chúng tôi! Chúng tôi sẽ trả lời cho quý khách trong thời gian sớm nhất.";

            }
            else
            {
                lblCaptchaMessage.InnerText = "Nhập sai mã xác nhận. Vui lòng thử lại";
            }
            pbTarget.Visible = true;
            ScriptManager.RegisterClientScriptBlock(
              recaptcha,
              recaptcha.GetType(),
              "recaptcha",
              "Recaptcha._init_options(RecaptchaOptions);"
              + "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
              + "{"
              + "  if ( RecaptchaOptions.custom_theme_widget )"
              + "  {"
              + "    Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
              + "    Recaptcha.challenge_callback();"
              + "  }"
              + "} else {"
              + "  if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
              + "  {"
              + "    jQuery(\"#" + pbTarget.ClientID + "\").html('<div id=\"recaptcha_widget_div\" style=\"display:none\"></div>');"
              + "    Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");"
              + "  }"
              + "  Recaptcha.reload();"
              + "  Recaptcha.challenge_callback();"
              + "}",
              true
            );
        }

        void ResetAllFields()
        {
            txtTitle.Text = "";
            txtName.Text = "";
            txtContent.Text = "";
            txtEmail.Text = "";
            txtPhone.Text = "";
        }
        protected void btnReset_Click(object sender, EventArgs e)
        {
            recaptcha.Validate();
            ResetAllFields();
            pbTarget.Visible = true;
            ScriptManager.RegisterClientScriptBlock(
              recaptcha,
              recaptcha.GetType(),
              "recaptcha",
              "Recaptcha._init_options(RecaptchaOptions);"
              + "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
              + "{"
              + "  if ( RecaptchaOptions.custom_theme_widget )"
              + "  {"
              + "    Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
              + "    Recaptcha.challenge_callback();"
              + "  }"
              + "} else {"
              + "  if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
              + "  {"
              + "    jQuery(\"#" + pbTarget.ClientID + "\").html('<div id=\"recaptcha_widget_div\" style=\"display:none\"></div>');"
              + "    Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");"
              + "  }"
              + "  Recaptcha.reload();"
              + "  Recaptcha.challenge_callback();"
              + "}",
              true
            );
        }
    }
}